package jp.lab3;

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.swing.JFrame;

public class WavPlayer {
        
        Clip clip;
        
        public WavPlayer(File audioFile){
                init(audioFile);
        }
        
        private void init(File audioFile){
                try {
                        AudioInputStream soundStream = AudioSystem.getAudioInputStream( audioFile );
                        AudioFormat audioFormat = soundStream.getFormat();
                        // define line information based on line type,
                        // encoding and frame sizes of audio file
                        DataLine.Info dataLineInfo = new DataLine.Info(
                                        Clip.class, AudioSystem.getTargetFormats(
                                                        AudioFormat.Encoding.PCM_SIGNED, audioFormat ),
                                                        audioFormat.getFrameSize(),
                                                        audioFormat.getFrameSize() * 2 );
        
                        // make sure sound system supports data line
                        if ( !AudioSystem.isLineSupported( dataLineInfo ) ) {
                                System.err.println( "Unsupported Clip File!" );
                                return;
                        }
                        // get clip line resource
                        clip = ( Clip ) AudioSystem.getLine( dataLineInfo );
                        // open audio clip and get required system resources
                        clip.open( soundStream );
                }
                catch ( Exception e) {
                        e.printStackTrace();
                }
        }
        
        public void play(){
                clip.start();
        }
        
        public static void main(String[] args) {
                JFrame frm=new JFrame("sound");
                
                WavPlayer clipPlayer = new WavPlayer(new File("recorded\\www.wav"));
                clipPlayer.play();

                frm.setSize(200, 300);
                frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frm.setVisible(true);
        }
}